package com.hzy.fivepalace.admin.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzy.fivepalace.admin.controller.base.BaseController;
import com.hzy.fivepalace.admin.dao.AdminUpdGoods;
import com.hzy.fivepalace.common.type.CouponsStatusEnums;
import com.hzy.fivepalace.common.type.VipTypeEnums;
import com.hzy.fivepalace.common.util.TableDataInfo;
import com.hzy.fivepalace.db.dao.*;
import com.hzy.fivepalace.db.dao.ex.*;
import com.hzy.fivepalace.db.domain.*;
import com.hzy.fivepalace.db.service.DtsGoodsService;
import com.hzy.fivepalace.db.service.DtsSystemConfigService;
import com.hzy.fivepalace.db.service.DtsUserService;
import com.hzy.fivepalace.db.vo.ReturnAdressVo;
import com.hzy.fivepalace.db.vo.admin.*;
import com.hzy.fivepalace.common.type.HtmlTypeEnums;
import com.hzy.fivepalace.common.type.WhetherTypeEnum;
import com.hzy.fivepalace.common.util.ResponseUtil;
import com.hzy.fivepalace.db.vo.wx.WxCategoryVo;
import com.hzy.fivepalace.db.vo.wx.WxHomeSlideshowVo;
import com.hzy.fivepalace.db.vo.wx.WxNewCategoryVo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 通用服务
 */
@Service
public class CommonService extends BaseController {


    @Resource
    private DtsGoodsMapper goodsMapper;

    @Resource
    private DtsCategoryMapperEx categoryMapper;

    @Resource
    private CommonMapperEx commonMapperEx;

    @Resource
    private DtsHtmlMapperEx htmlMapperEx;

    @Resource
    private Redisson redisson;

    @Resource
    private DtsHomeIndexMapperEx homeIndexMapperEx;

    @Resource
    private DtsTopicMapper topicMapper;

    @Autowired
    private DtsSystemConfigService systemConfigService;

    @Resource
    private DtsFeedbackMapper feedbackMapper;

    @Resource
    private DtsUserService userService;

    @Resource
    private DtsGiveVipLogMapper dtsGiveVipLogMapper;

    @Resource
    private DtsHomeIndexMapper homeIndexMapper;

    @Resource
    private DtsHomeChildMapper homeChildMapper;

    @Resource
    private DtsHomeGoodsMapper homeGoodsMapper;

    @Resource
    private DtsVideoMapper videoMapper;


    @Resource
    private DtsVipConfigMapper dtsVipConfigMapper;

    @Resource
    private DtsCouponMapper couponMapper;

    @Resource
    private DtsCouponUserMapperEx couponUserMapperEx;

    @Autowired
    private DtsGoodsService goodsService;

    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(16, 16, 1000, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);


    /**
     * 赠送会员
     *
     * @param userId
     * @param vipType
     * @param msg     赠送原因,可不填
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object giveVip(Integer userId, Integer vipType, String msg) {
        if (null == userId || userId.intValue() < 1) {
            return ResponseUtil.fail("参数【userId】为空");
        }
        if (null == vipType) {
            return ResponseUtil.fail("参数【vipType】为空");
        }
        RLock lock = redisson.getLock("admin_giveVip_" + userId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        VipTypeEnums vipTypeEnums = VipTypeEnums.getEnum(vipType);
        if (null == VipTypeEnums.getEnum(vipType)) {
            lock.unlock();
            return ResponseUtil.fail("会员类型错误");
        }
        DtsUser user = userService.selectById(userId);
        if (null == user) {
            lock.unlock();
            return ResponseUtil.fail("用户不存在");
        }
        if (user.getVipType().equals(vipType)) {
            lock.unlock();
            return ResponseUtil.fail("该用户已是" + vipTypeEnums.getDesc());
        }
        if (vipType.intValue() < user.getVipType().intValue()) {
            lock.unlock();
            return ResponseUtil.fail("无法赠送比当前小的会员");
        }
        if (StringUtils.isBlank(msg)) {
            msg = "";
        }

        DtsUser userUpd = new DtsUser();
        userUpd.setId(user.getId());
        userUpd.setVipType(vipType);
        userService.updateById(userUpd);
        //记录赠送日志
        DtsGiveVipLog record = new DtsGiveVipLog();
        record.setCreateId(getAdminId());
        record.setCreateTime(LocalDateTime.now());
        record.setMsg(msg);
        record.setUserId(userId);
        record.setVipType(vipType);
        dtsGiveVipLogMapper.insertSelective(record);

        DtsVipConfigExample example = new DtsVipConfigExample();
        example.orderBy("id desc");
        example.createCriteria().andVipTypeEqualTo(vipType);
        DtsVipConfig vipConfig=dtsVipConfigMapper.selectOneByExampleWithBLOBs(example);
        if(null!=vipConfig&&null!=vipConfig.getCouponId()&&!vipConfig.getCouponId().equals(0)){
            DtsCoupon coupon = couponMapper.selectByPrimaryKey(vipConfig.getCouponId());
            if (null != coupon && !coupon.getDeleted() && coupon.getStatus().intValue() == 0) {
                DtsCouponUser couponUserAdd = new DtsCouponUser();
                couponUserAdd.setCouponId(vipConfig.getCouponId());
                couponUserAdd.setAddTime(LocalDateTime.now());
                couponUserAdd.setUpdateTime(LocalDateTime.now());
                couponUserAdd.setUserId(userId);
                couponUserAdd.setStatus((short) CouponsStatusEnums.TYPE0.getId());
                couponUserAdd.setStartTime(LocalDateTime.now());
                couponUserAdd.setEndTime(LocalDateTime.now().plusDays(coupon.getDays()));
                couponUserAdd.setDeleted(false);
                couponUserMapperEx.insertSelective(couponUserAdd);
            }
        }


        lock.unlock();
        return ResponseUtil.ok("赠送成功");
    }

    /**
     * 获取会员配置列表
     *
     * @param page
     * @param size
     * @return
     */
    public TableDataInfo getVipConfigList(Integer page, Integer size) {
        DtsVipConfigExample example = new DtsVipConfigExample();
        example.setOrderByClause("by_price asc");
        Page p = PageHelper.startPage(page, size);
        List<DtsVipConfig> list = dtsVipConfigMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }else{
            list.forEach(item->{
                DtsCoupon bindCoupon=null;
                if(null!=item.getCouponId()&&!item.getCouponId().equals(0)){
                    DtsCoupon coupon = couponMapper.selectByPrimaryKey(item.getCouponId());
                    if (null != coupon && !coupon.getDeleted() && coupon.getStatus().intValue() == 0) {
                        bindCoupon=coupon;
                    }
                }

                if(null==bindCoupon){
                    item.setCouponId(0);
                }else{
                    item.setBindCoupon(bindCoupon);
                }

            });
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }


    /**
     * 获取vip配置详情
     *
     * @param vipId
     * @return
     */
    public Object getVipConfigDetail(Long vipId) {

        DtsVipConfig vipInfo = dtsVipConfigMapper.selectByPrimaryKey(vipId);
        if (null == vipInfo || vipInfo.getDeleted()) {
            return ResponseUtil.fail("会员商品不存在");
        }

        DtsCoupon bindCoupon=null;
        if(null!=vipInfo.getCouponId()&&!vipInfo.getCouponId().equals(0)){
            DtsCoupon coupon = couponMapper.selectByPrimaryKey(vipInfo.getCouponId());
            if (null != coupon && !coupon.getDeleted() && coupon.getStatus().intValue() == 0) {
                bindCoupon=coupon;
            }
        }

        if(null==bindCoupon){
            vipInfo.setCouponId(0);
        }else{
            vipInfo.setBindCoupon(bindCoupon);
        }


        Map<String, Object> data = new HashMap<>();
        data.put("vipInfo", vipInfo);
        DtsGoods info = goodsService.getVipGoodsById(vipInfo.getGoodsId());
        if (null != info) {
            info.setCounterPrice(vipInfo.getByPrice());
            info.setRetailPrice(vipInfo.getByPrice());
            info.setWholesalePrice(vipInfo.getByPrice());
            info.setSales(vipInfo.getSales().intValue());
            data.put("goodsInfo", info);
        }
        return ResponseUtil.ok(data);
    }

    /**
     * 修改会员配置
     *
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object updateVipConfig(DtsVipConfig vipConfig, String goodsInfo) {
        if (null == vipConfig.getId()) {
            return ResponseUtil.fail("参数【id】为空");
        }

        RLock lock = redisson.getLock("admin_updateVipConfig_" + vipConfig.getId());
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        if (null == vipConfig.getByPrice()) {
            lock.unlock();
            return ResponseUtil.fail("请填写价格");
        }
        if (vipConfig.getByPrice().compareTo(new BigDecimal("0")) <= 0) {
            lock.unlock();
            return ResponseUtil.fail("价格必须大于0");
        }
        if (StrUtil.isEmpty(vipConfig.getVipName())) {
            lock.unlock();
            return ResponseUtil.fail("会员名称不能为空");
        }

        DtsVipConfig oldVipConfig = dtsVipConfigMapper.selectByPrimaryKey(vipConfig.getId());
        if (null == oldVipConfig || oldVipConfig.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("数据不存在");
        }
        if (null == vipConfig.getOneLevelExtendAmount()) {
            lock.unlock();
            return ResponseUtil.fail("请填写一级推广金额");
        }
        if (null == vipConfig.getTwoLevelExtendAmount()) {
            lock.unlock();
            return ResponseUtil.fail("请填写二级推广金额");
        }

        if (null == vipConfig.getGoodsOneLevelExtendScale()) {
            lock.unlock();
            return ResponseUtil.fail("请填写商品默认一级推广比例");
        }
        if (vipConfig.getOneLevelExtendAmount().compareTo(new BigDecimal("0")) <= 0) {
            vipConfig.setOneLevelExtendAmount(new BigDecimal("0"));
        }
        if (vipConfig.getTwoLevelExtendAmount().compareTo(new BigDecimal("0")) <= 0) {
            vipConfig.setTwoLevelExtendAmount(new BigDecimal("0"));
        }
        if (vipConfig.getGoodsOneLevelExtendScale().compareTo(new BigDecimal("0")) <= 0) {
            vipConfig.setGoodsOneLevelExtendScale(new BigDecimal("0"));
        }

        if (oldVipConfig.getVipType().intValue() == VipTypeEnums.TYPE1.getId()) {
            vipConfig.setGoodsTwoLevelExtendScale(new BigDecimal("0"));
        } else {
            if (null == vipConfig.getGoodsTwoLevelExtendScale()) {
                lock.unlock();
                return ResponseUtil.fail("请填写商品默认二级推广比例");
            }
            if (vipConfig.getGoodsTwoLevelExtendScale().compareTo(new BigDecimal("0")) <= 0) {
                vipConfig.setGoodsTwoLevelExtendScale(new BigDecimal("0"));
            }
        }

        DtsGoods goodsInfos = null;
        if (!StringUtils.isBlank(goodsInfo)) {
            try {
                goodsInfos = com.alibaba.fastjson2.JSONObject.parseObject(goodsInfo, DtsGoods.class);
            } catch (Exception e) {
                lock.unlock();
                return ResponseUtil.fail("解析异常,参数错误");
            }
        }

        if (null != goodsInfos && null != oldVipConfig.getGoodsId()) {
            if (!StringUtils.isBlank(goodsInfos.getName()) && goodsInfos.getName().length() > 150) {
                lock.unlock();
                return ResponseUtil.fail("商品名称最多150个字");
            }
            if (!StringUtils.isBlank(goodsInfos.getKeywords()) && goodsInfos.getKeywords().length() > 200) {
                lock.unlock();
                return ResponseUtil.fail("商品关键字长度最多200");
            }
            if (!StringUtils.isBlank(goodsInfos.getBrief()) && goodsInfos.getBrief().length() > 300) {
                lock.unlock();
                return ResponseUtil.fail("商品简介最多300个字");
            }
            if (!StringUtils.isBlank(goodsInfos.getGoodsSn()) && goodsInfos.getGoodsSn().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("商品编码最多50位");
            }
            if (!StringUtils.isBlank(goodsInfos.getUnit()) && goodsInfos.getUnit().length() > 10) {
                lock.unlock();
                return ResponseUtil.fail("商品单位最多10个字");
            }
            DtsGoods infoUpd = new DtsGoods();
            BeanUtils.copyProperties(goodsInfos, infoUpd);
            infoUpd.setId(oldVipConfig.getGoodsId());
            infoUpd.setCategoryId(-100);
            infoUpd.setCategoryIdNew(-100);
            infoUpd.setDeleted(true);
            infoUpd.setIsSince(false);
            infoUpd.setIsOnSale(false);
            infoUpd.setUpdateTime(LocalDateTime.now());
            goodsMapper.updateByPrimaryKeySelective(infoUpd);
        }


        DtsVipConfig vipConfigUpd = new DtsVipConfig();
        vipConfigUpd.setId(vipConfig.getId());
        vipConfigUpd.setVipName(vipConfig.getVipName());
        vipConfigUpd.setOneLevelExtendAmount(vipConfig.getOneLevelExtendAmount());
        vipConfigUpd.setGoodsOneLevelExtendScale(vipConfig.getGoodsOneLevelExtendScale());
        vipConfigUpd.setTwoLevelExtendAmount(vipConfig.getTwoLevelExtendAmount());
        vipConfigUpd.setGoodsTwoLevelExtendScale(vipConfig.getGoodsTwoLevelExtendScale());
        vipConfigUpd.setSales(vipConfig.getSales());
        vipConfigUpd.setByPrice(vipConfig.getByPrice());
        vipConfigUpd.setUpdateTime(LocalDateTime.now());
        vipConfigUpd.setCouponId(vipConfig.getCouponId());
        dtsVipConfigMapper.updateByPrimaryKeySelective(vipConfigUpd);


        lock.unlock();
        return ResponseUtil.ok("修改成功");
    }


    /**
     * 获取新分类下拉选
     *
     * @return
     */
    public Object getNewCategorySelect() {
        List<WxNewCategoryVo> list = categoryMapper.wxGetNewCategoryList();
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return ResponseUtil.ok(list);
    }


    /**
     * 用户下拉选列表
     *
     * @param phone
     * @return
     */
    public Object selectEntity(String phone) {
        if (StringUtils.isBlank(phone)) {
            return ResponseUtil.fail("手机号为空");
        }
        return commonMapperEx.selectEntity(phone);
    }

    /**
     * 静态页面列表
     *
     * @param type
     * @return
     */
    public Object getHtmlList(Integer type) {
        if (null != type) {
            if (null == HtmlTypeEnums.getEnum(type)) {
                return ResponseUtil.fail("检索类型错误");
            }
        }
        List<AdminHtmlListVo> list = htmlMapperEx.getHtmlListSys(WhetherTypeEnum.NO.getName(), type);
        list.forEach(item -> {
            item.setTypeName(HtmlTypeEnums.getEnum(item.getType()).getDesc());
        });
        return ResponseUtil.ok(list);
    }

    /**
     * 静态页面详情
     *
     * @param id
     * @return
     */
    public Object getHtmlDetails(Integer id) {
        //根据id查询
        DtsHtml html = htmlMapperEx.selectByPrimaryKey(id);
        if (null == html || html.getIsDel()) {
            return ResponseUtil.fail("数据不存在");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("content", html.getContent());
        return ResponseUtil.ok(result);
    }

    /**
     * 修改静态页面
     *
     * @param id
     * @param content
     * @return
     */
    public Object updHtml(Integer id, String content) {

        RLock lock = redisson.getLock("admin_updHtml_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        if (StringUtils.isBlank(content)) {
            lock.unlock();
            return ResponseUtil.fail("内容不能为空");
        }

        //根据id查询
        DtsHtml html = htmlMapperEx.selectByPrimaryKey(id);
        if (null == html || html.getIsDel()) {
            return ResponseUtil.fail("数据不存在");
        }
        html.setContent(content);
        html.setUpdateTime(LocalDateTime.now());
        htmlMapperEx.updateByPrimaryKeySelective(html);
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }

    /**
     * 获取首页轮播图
     *
     * @return
     */
    public Object getHomeSlideshow() {
        List<WxHomeSlideshowVo> list = homeIndexMapperEx.getHomeSlideshow();
        return ResponseUtil.ok(list);
    }

    /**
     * 删除轮播图
     *
     * @param id
     * @return
     */
    public Object delBanner(Integer id) {
        RLock lock = redisson.getLock("admin_delBanner_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        DtsTopic topic = topicMapper.selectByPrimaryKey(id);
        if (null == topic) {
            return ResponseUtil.fail("数据不存在");
        }
        topic.setUpdateTime(LocalDateTime.now());
        topic.setDeleted(true);
        topicMapper.updateByPrimaryKeySelective(topic);
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }

    /**
     * 新增首页轮播图
     *
     * @param imgUrl
     * @param jumpUrl
     * @param sort
     * @return
     */
    public Object addBanner(String imgUrl, String jumpUrl, Integer sort) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_addBanner_" + adminId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (StringUtils.isBlank(imgUrl)) {
            lock.unlock();
            return ResponseUtil.fail("未上传图片");
        }
        if (null == sort || sort.intValue() < 0) {
            sort = 0;
        }
        DtsTopic record = new DtsTopic();
        record.setDeleted(false);
        record.setAddTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        record.setSortOrder(sort);
        record.setPicUrl(imgUrl);
        record.setShareUrl(jumpUrl);
        topicMapper.insertSelective(record);
        lock.unlock();
        return ResponseUtil.ok("新增成功", null);
    }

    /**
     * 修改首页轮播图
     *
     * @param imgUrl
     * @param jumpUrl
     * @param sort
     * @param id
     * @return
     */
    public Object updBanner(String imgUrl, String jumpUrl, Integer sort, Integer id) {
        RLock lock = redisson.getLock("admin_updBanner_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (StringUtils.isBlank(imgUrl)) {
            lock.unlock();
            return ResponseUtil.fail("未上传图片");
        }
        if (StringUtils.isBlank(jumpUrl)) {
            jumpUrl = "";
        }
        if (null == sort || sort.intValue() < 0) {
            sort = 0;
        }
        DtsTopic record = topicMapper.selectByPrimaryKey(id);
        if (null == record || record.getDeleted()) {
            return ResponseUtil.fail("数据不存在");
        }
        record.setUpdateTime(LocalDateTime.now());
        record.setSortOrder(sort);
        record.setPicUrl(imgUrl);
        record.setShareUrl(jumpUrl);
        topicMapper.updateByPrimaryKeySelective(record);
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }

    /**
     * 类目列表-分页
     *
     * @param page
     * @param size
     * @return
     */
    public TableDataInfo getCategoryListPage(Integer page, Integer size) {

        Page p = PageHelper.startPage(page, size);
        List<WxCategoryVo> list = categoryMapper.wxGetCategoryList();
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }

    /**
     * 一级类目列表-不分页
     *
     * @return
     */
    public Object getCategoryList() {

        List<WxCategoryVo> list = categoryMapper.wxGetCategoryList();
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return ResponseUtil.ok(list);
    }

    /**
     * 新增或修改首页类目
     *
     * @param vo
     * @param sort
     * @return
     */
    public Object addCategoryOrUpd(WxCategoryVo vo, Integer sort) {

        Integer adminId = getAdminId();
        if (null == vo.getCategoryId()) {//新增
            RLock lock = redisson.getLock("admin_addCategory_" + adminId);
            if (lock.isLocked()) {
                return ResponseUtil.frequent();
            }
            lock.lock(30, TimeUnit.SECONDS);
            if (StringUtils.isBlank(vo.getCategorynNme())) {
                lock.unlock();
                return ResponseUtil.fail("类目名称不能为空");
            }
            if (vo.getCategorynNme().length() > 10) {
                lock.unlock();
                return ResponseUtil.fail("类目名称最多10个字");
            }
            if (StringUtils.isBlank(vo.getPicUrl())) {
                lock.unlock();
                return ResponseUtil.fail("未上传类目图片");
            }
            if (StringUtils.isBlank(vo.getDesc())) {
                lock.unlock();
                return ResponseUtil.fail("类目描述不能为空");
            }
            if (vo.getCategorynNme().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("类目描述最多50个字");
            }
            if (null == sort || sort.intValue() < 0) {
                sort = 0;
            }
            DtsCategory record = new DtsCategory();
            record.setName(vo.getCategorynNme());
            record.setPicUrl(vo.getPicUrl());
            record.setPid(0);
            record.setDeleted(false);
            record.setLevel("L1");
            record.setAddTime(LocalDateTime.now());
            record.setDesc(vo.getDesc());
            record.setUpdateTime(LocalDateTime.now());
            record.setSortOrder(sort.byteValue());
            record.setIsHome(true);
            categoryMapper.insertSelective(record);
            lock.unlock();
            return ResponseUtil.ok("新增成功", null);
        } else {//修改
            RLock lock = redisson.getLock("admin_updCategory_" + vo.getCategoryId());
            if (lock.isLocked()) {
                return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
            }
            lock.lock(30, TimeUnit.SECONDS);
            DtsCategory category = categoryMapper.selectByPrimaryKey(vo.getCategoryId());
            if (null == category || category.getDeleted() || !category.getIsHome()) {
                lock.unlock();
                return ResponseUtil.fail("类目不存在");
            }
            if (StringUtils.isBlank(vo.getCategorynNme())) {
                vo.setCategorynNme(null);
            }
            if (!StringUtils.isBlank(vo.getCategorynNme()) && vo.getCategorynNme().length() > 10) {
                lock.unlock();
                return ResponseUtil.fail("类目名称最多10个字");
            }
            if (StringUtils.isBlank(vo.getPicUrl())) {
                vo.setPicUrl(null);
            }
            if (StringUtils.isBlank(vo.getDesc())) {
                vo.setDesc(null);
            }
            if (!StringUtils.isBlank(vo.getDesc()) && vo.getCategorynNme().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("类目描述最多50个字");
            }
            DtsCategory record = new DtsCategory();
            record.setId(vo.getCategoryId());
            record.setName(vo.getCategorynNme());
            record.setPicUrl(vo.getPicUrl());
            record.setDesc(vo.getDesc());
            record.setUpdateTime(LocalDateTime.now());
            if (null != sort) {
                record.setSortOrder(sort.byteValue());
            }
            categoryMapper.updateByPrimaryKeySelective(record);
            lock.unlock();
            return ResponseUtil.ok("修改成功", null);
        }
    }

    /**
     * 删除首页类目
     *
     * @param categoryId
     * @return
     */
    public Object delCategory(Integer categoryId) {
        RLock lock = redisson.getLock("admin_delCategory_" + categoryId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        DtsCategory category = categoryMapper.selectByPrimaryKey(categoryId);
        if (null == category || category.getDeleted() || !category.getIsHome()) {
            lock.unlock();
            return ResponseUtil.fail("类目不存在");
        }
        //判断该分类下是否存在有效商品
        if (categoryMapper.isExistGoods(categoryId, 1)) {
            lock.unlock();
            return ResponseUtil.fail("该类目下存在有效商品,无法删除");
        }
        category.setUpdateTime(LocalDateTime.now());
        category.setDeleted(true);
        categoryMapper.updateByPrimaryKeySelective(category);
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }

    /**
     * 意见反馈列表
     *
     * @param content
     * @param page
     * @param size
     * @return
     */
    public TableDataInfo feedbackList(String content, Integer page, Integer size) {
        DtsFeedbackExample example = new DtsFeedbackExample();
        example.orderBy("add_time desc");
        if (StringUtils.isBlank(content)) {
            example.createCriteria().andDeletedEqualTo(false);
        } else {
            example.createCriteria().andDeletedEqualTo(false).andContentLike("%" + content + "%");
        }

        Page p = PageHelper.startPage(page, size);
        List<DtsFeedback> list = feedbackMapper.selectByExample(example);
        List<Map<String, Object>> feedbackInfoList = new ArrayList<>();
        list.forEach(item -> {
            Map<String, Object> vo = new HashMap<>();
            vo.put("addTime", item.getAddTime());
            vo.put("content", item.getContent());
            vo.put("picUrls", (null == item.getPicUrls() || item.getPicUrls().length < 1) ? new String[]{} : item.getPicUrls());
            //获取评论用户信息
            vo.put("userInfo", userService.getUserNickNameAndPhoneAndAvatar(item.getUserId()));
            feedbackInfoList.add(vo);
        });

        return TableDataInfo.getDataTable(feedbackInfoList, p.getTotal());
    }

    /**
     * 修改运费配置
     *
     * @param freeFreightMoney
     * @param freight
     * @return
     */
    public Object updFreightConfig(BigDecimal freeFreightMoney, BigDecimal freight) {
        RLock lock = redisson.getLock("admin_updFreightConfig");
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (null == freeFreightMoney || freeFreightMoney.compareTo(new BigDecimal(0)) <= 0) {
            freeFreightMoney = new BigDecimal("0.00");
        }
        if (null == freight || freight.compareTo(new BigDecimal(0)) <= 0) {
            freight = new BigDecimal("0.00");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("freeFreightMoney", freeFreightMoney);
        map.put("freight", freight);
        DtsSystem dtsSystem = systemConfigService.selectByKey("dts.freight");
        if (null != dtsSystem) {
            dtsSystem.setKeyValue(JSON.toJSONString(map));
            dtsSystem.setUpdateTime(LocalDateTime.now());
            systemConfigService.updateByPrimaryKeySelective(dtsSystem);
        } else {
            dtsSystem = new DtsSystem();
            dtsSystem.setKeyValue(JSON.toJSONString(map));
            dtsSystem.setAddTime(LocalDateTime.now());
            dtsSystem.setDeleted(false);
            dtsSystem.setKeyName("dts.freight");
            systemConfigService.insertSelective(dtsSystem);
        }
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }

    /**
     * 运费配置详情
     *
     * @return
     */
    public Object getFreightConfigDetails() {
        Map<String, Object> result = new HashMap<>();
        //免费包邮金额
        BigDecimal freeFreightMoney = new BigDecimal("0.00");
        //不满足免费包邮时运费
        BigDecimal freight = new BigDecimal("0.00");
        //读取系统配置表
        DtsSystem dtsSystem = systemConfigService.selectByKey("dts.freight");
        if (null != dtsSystem) {
            String jsonStr = dtsSystem.getKeyValue();
            JSONObject json = JSONObject.parseObject(jsonStr);
            if (null != json) {
                if (null != json.getBigDecimal("freeFreightMoney")) {
                    freeFreightMoney = json.getBigDecimal("freeFreightMoney");
                }
                if (null != json.getBigDecimal("freight")) {
                    freight = json.getBigDecimal("freight");
                }
            }
        }
        result.put("freeFreightMoney", freeFreightMoney);
        result.put("freight", freight);
        return ResponseUtil.ok(result);
    }

    /**
     * 首页模块列表-父级
     *
     * @param content
     * @param page
     * @param size
     * @return
     */
    public TableDataInfo getHomeModuleParentList(String content, Integer page, Integer size) {
        Page p = PageHelper.startPage(page, size);
        List<AdminHomeModuleParentVo> list = commonMapperEx.getHomeModuleParentList(content);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }

    /**
     * 删除首页模块-父级
     *
     * @param indexId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object delHomeModuleParent(Integer indexId) {
        RLock lock = redisson.getLock("admin_delHomeModuleParent_" + indexId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        DtsHomeIndex homeIndex = homeIndexMapper.selectByPrimaryKey(indexId);
        if (null == homeIndex) {
            lock.unlock();
            return ResponseUtil.fail("数据不存在");

        }
        homeIndexMapper.deleteByPrimaryKey(indexId);
        //查询二级信息
        DtsHomeChildExample homeChildExampleQuery = new DtsHomeChildExample();
        homeChildExampleQuery.orderBy("add_time desc");
        homeChildExampleQuery.createCriteria().andIndexIdEqualTo(indexId);
        DtsHomeChild homeChild = homeChildMapper.selectOneByExample(homeChildExampleQuery);
        //删除二级
        DtsHomeChildExample homeChildExample = new DtsHomeChildExample();
        homeChildExample.createCriteria().andIndexIdEqualTo(indexId);
        homeChildMapper.deleteByExample(homeChildExample);
        //删除三级（也就是商品）
        if (null != homeChild) {
            DtsHomeGoodsExample example = new DtsHomeGoodsExample();
            example.createCriteria().andPidEqualTo(homeChild.getId());
            homeGoodsMapper.deleteByExample(example);
        }
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }

    /**
     * 新增或修改首页模块-父级
     *
     * @param vo
     * @return
     */
    public Object addOrUpdHomeModuleParent(AdminHomeModuleParentVo vo) {
        Integer adminId = getAdminId();
        if (null == vo.getIndexId() || vo.getIndexId().intValue() < 1) {//新增
            RLock lock = redisson.getLock("admin_addHomeModuleParent_" + adminId);
            if (lock.isLocked()) {
                return ResponseUtil.frequent();
            }
            lock.lock(30, TimeUnit.SECONDS);
            if (StringUtils.isBlank(vo.getIndexName())) {
                lock.unlock();
                return ResponseUtil.fail("名称不能为空");
            }
            if (vo.getIndexName().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("名称最多50字");
            }
            if (StringUtils.isBlank(vo.getIndexDescription())) {
                lock.unlock();
                return ResponseUtil.fail("描述不能为空");
            }
            if (vo.getIndexDescription().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("描述最多50字");
            }
            if (StringUtils.isBlank(vo.getIndexImgUrl())) {
                lock.unlock();
                return ResponseUtil.fail("请上传图片");
            }
            if (null == vo.getSort() || vo.getSort().intValue() < 1) {
                vo.setSort(0);
            }
            DtsHomeIndex homeIndex = new DtsHomeIndex();
            homeIndex.setCreateId(adminId);
            homeIndex.setAddTime(LocalDateTime.now());
            homeIndex.setName(vo.getIndexName());
            homeIndex.setDescription(vo.getIndexDescription());
            homeIndex.setImgUrl(vo.getIndexImgUrl());
            homeIndex.setSort(vo.getSort());
            homeIndexMapper.insertSelective(homeIndex);
            lock.unlock();
            return ResponseUtil.ok("新增成功", null);
        } else {//修改
            RLock lock = redisson.getLock("admin_updHomeModuleParent_" + vo.getIndexId());
            if (lock.isLocked()) {
                return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
            }
            lock.lock(30, TimeUnit.SECONDS);
            if (StringUtils.isBlank(vo.getIndexName())) {
                vo.setIndexName(null);
            }
            if (!StringUtils.isBlank(vo.getIndexName()) && vo.getIndexName().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("名称最多50字");
            }
            if (StringUtils.isBlank(vo.getIndexDescription())) {
                vo.setIndexDescription(null);
            }
            if (!StringUtils.isBlank(vo.getIndexDescription()) && vo.getIndexDescription().length() > 50) {
                lock.unlock();
                return ResponseUtil.fail("描述最多50字");
            }
            if (StringUtils.isBlank(vo.getIndexImgUrl())) {
                vo.setIndexImgUrl(null);
            }
            DtsHomeIndex homeIndex = homeIndexMapper.selectByPrimaryKey(vo.getIndexId());
            if (null == homeIndex) {
                lock.unlock();
                return ResponseUtil.fail("数据不存在");
            }
            homeIndex.setCreateId(adminId);
            homeIndex.setName(vo.getIndexName());
            homeIndex.setDescription(vo.getIndexDescription());
            homeIndex.setImgUrl(vo.getIndexImgUrl());
            homeIndex.setSort(vo.getSort());
            homeIndexMapper.updateByPrimaryKeySelective(homeIndex);
            lock.unlock();
            return ResponseUtil.ok("修改成功", null);
        }

    }

    /**
     * 新增模块商品
     *
     * @param childId
     * @param goodsIds
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object addHomeModuleGoods(Integer childId, String goodsIds) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_addHomeModuleGoods_" + adminId + childId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        DtsHomeChild homeChild = homeChildMapper.selectByPrimaryKey(childId);
        if (null == homeChild) {
            lock.unlock();
            return ResponseUtil.fail("上级标签不存在");
        }
        if (StringUtils.isBlank(goodsIds)) {
            lock.unlock();
            return ResponseUtil.fail("未选择商品");
        }
        String[] goodsArry = goodsIds.split(",");
        if (null == goodsArry && goodsArry.length < 1) {
            lock.unlock();
            return ResponseUtil.fail("未选择商品");
        }
        for (String id : goodsArry) {
            DtsHomeGoods homeGoods = new DtsHomeGoods();
            homeGoods.setGoodsId(Integer.parseInt(id));
            homeGoods.setAddTime(LocalDateTime.now());
            homeGoods.setCreateId(adminId);
            homeGoods.setPid(childId);
            homeGoodsMapper.insertSelective(homeGoods);
        }
        lock.unlock();
        return ResponseUtil.ok("新增成功", null);
    }

    /**
     * 删除模块商品
     *
     * @param childId
     * @param goodsIds
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object delHomeModuleGoods(Integer childId, String goodsIds) {
        RLock lock = redisson.getLock("admin_delHomeModuleGoods_" + childId + goodsIds);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        DtsHomeChild homeChild = homeChildMapper.selectByPrimaryKey(childId);
        if (null == homeChild) {
            lock.unlock();
            return ResponseUtil.fail("上级标签不存在");
        }
        if (StringUtils.isBlank(goodsIds)) {
            lock.unlock();
            return ResponseUtil.fail("未选择商品");
        }
        String[] goodsArry = goodsIds.split(",");
        if (null == goodsArry && goodsArry.length < 1) {
            lock.unlock();
            return ResponseUtil.fail("未选择商品");
        }
        List<Integer> goodsIdList = new ArrayList<>();
        for (String id : goodsArry) {
            goodsIdList.add(Integer.parseInt(id));
        }
        if (!CollectionUtils.isEmpty(goodsIdList)) {
            DtsHomeGoodsExample example = new DtsHomeGoodsExample();
            example.createCriteria().andGoodsIdIn(goodsIdList).andPidEqualTo(childId);
            homeGoodsMapper.deleteByExample(example);
        }
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }

    /**
     * 新增首页模块-子级
     *
     * @param vo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object addHomeModuleChild(AdminAddHomeModuleChildVo vo) {
        if (null == vo.getIndexId()) {
            return ResponseUtil.fail("父级id为空");
        }
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_addHomeModuleChild_" + adminId + vo.getIndexId());
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);

        if (StringUtils.isBlank(vo.getLabelName())) {
            lock.unlock();
            return ResponseUtil.fail("标签名称不能为空");
        }
        if (vo.getLabelName().length() > 10) {
            lock.unlock();
            return ResponseUtil.fail("标签名称最多10个字");
        }
        DtsHomeIndex homeIndex = homeIndexMapper.selectByPrimaryKey(vo.getIndexId());
        if (null == homeIndex) {
            lock.unlock();
            return ResponseUtil.fail("父级数据不存在");
        }
        //判断当前父级下面有几个二级了
        DtsHomeChildExample example = new DtsHomeChildExample();
        example.createCriteria().andIndexIdEqualTo(homeIndex.getId());
        if (homeChildMapper.countByExample(example) >= 2) {
            lock.unlock();
            return ResponseUtil.fail("最多添加两个分类");
        }
        DtsHomeChild homeChildAdd = new DtsHomeChild();
        homeChildAdd.setAddTime(LocalDateTime.now());
        homeChildAdd.setCreateId(adminId);
        homeChildAdd.setIndexId(vo.getIndexId());
        homeChildAdd.setName(vo.getLabelName());
        homeChildMapper.insertSelective(homeChildAdd);
        lock.unlock();
        return ResponseUtil.ok("新增成功", null);
    }

    /**
     * 修改首页模块-子级
     *
     * @param vo
     * @return
     */
    public Object updHomeModuleChild(AdminUpdHomeModuleChildVo vo) {
        if (null == vo.getChildId()) {
            return ResponseUtil.fail("参数【childId】为空");
        }
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_updHomeModuleChild_" + adminId + vo.getChildId());
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        if (StringUtils.isBlank(vo.getLabelName())) {
            vo.setLabelName(null);
        }
        if (!StringUtils.isBlank(vo.getLabelName()) && vo.getLabelName().length() > 10) {
            lock.unlock();
            return ResponseUtil.fail("标签名称最多10个字");
        }
        DtsHomeChild homeChild = homeChildMapper.selectByPrimaryKey(vo.getChildId());
        if (null == homeChild) {
            lock.unlock();
            return ResponseUtil.fail("数据不存在");
        }
        homeChild.setName(vo.getLabelName());
        homeChildMapper.updateByPrimaryKeySelective(homeChild);
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }


    /**
     * 首页模块列表-子级-不分页
     *
     * @param content
     * @param page
     * @param size
     * @param indexId
     * @return
     */
    public Object getHomeModuleChildList(String content, Integer page, Integer size, Integer indexId) {

        DtsHomeIndex homeIndex = homeIndexMapper.selectByPrimaryKey(indexId);
        if (null == homeIndex) {
            return TableDataInfo.errorDataTable("父级数据不存在");
        }
        List<AdminHomeModuleChildVo> list = commonMapperEx.getHomeModuleChildList(content, indexId);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return ResponseUtil.ok(list);
    }

    /**
     * 删除首页模块-子级(包含下面所有商品)
     *
     * @param childId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object delHomeModuleChild(Integer childId) {
        RLock lock = redisson.getLock("admin_delHomeModuleChild_" + childId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        //查询二级信息
        DtsHomeChild homeChild = homeChildMapper.selectByPrimaryKey(childId);
        if (null == homeChild) {
            lock.unlock();
            return ResponseUtil.fail("数据不存在");
        }
        //删除二级
        homeChildMapper.deleteByPrimaryKey(childId);
        //删除三级（也就是商品）
        if (null != homeChild) {
            DtsHomeGoodsExample example = new DtsHomeGoodsExample();
            example.createCriteria().andPidEqualTo(homeChild.getId());
            homeGoodsMapper.deleteByExample(example);
        }
        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }


    /**
     * 新增视频
     *
     * @param video
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object addVideo(DtsVideo video) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_addVideo_" + adminId);
        if (lock.isLocked()) {
            return ResponseUtil.frequent();
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (!StringUtils.isBlank(video.getTitle()) && video.getTitle().length() > 250) {
            lock.unlock();
            return ResponseUtil.fail("标题最多250字");
        }
        if (null != video.getRecommend() && video.getRecommend()) {//如果设置为推荐，就取消当前所有的推荐视频
            DtsVideo updVideo = new DtsVideo();
            updVideo.setRecommend(false);
            updVideo.setUpdateId(adminId);
            updVideo.setUpdateTime(LocalDateTime.now());
            DtsVideoExample updeEample = new DtsVideoExample();
            updeEample.createCriteria().andRecommendEqualTo(true);
            videoMapper.updateByExampleSelective(updVideo, updeEample);
        }
        if (null == video.getSort() || video.getSort().intValue() <= 0) {
            video.setSort(0);
        }
        video.setAddId(adminId);
        video.setAddTime(LocalDateTime.now());
        videoMapper.insertSelective(video);
        lock.unlock();
        return ResponseUtil.ok("新增成功", null);
    }


    /**
     * 设置为推荐视频
     *
     * @param id
     * @return
     */
    public Object setVideoRecommend(Integer id) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_setVideoRecommend_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        DtsVideo videoOld = videoMapper.selectByPrimaryKey(id);
        if (null == videoOld || videoOld.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("视频不存在或已删除");
        }
        //取消当前所有的推荐视频
        DtsVideo updVideo = new DtsVideo();
        updVideo.setRecommend(false);
        updVideo.setUpdateId(adminId);
        updVideo.setUpdateTime(LocalDateTime.now());
        DtsVideoExample updeEample = new DtsVideoExample();
        updeEample.createCriteria().andRecommendEqualTo(true);
        videoMapper.updateByExampleSelective(updVideo, updeEample);


        videoOld.setRecommend(true);
        videoOld.setUpdateId(adminId);
        videoOld.setUpdateTime(LocalDateTime.now());
        videoMapper.updateByPrimaryKeySelective(videoOld);

        lock.unlock();
        return ResponseUtil.ok("设置成功", null);
    }

    /**
     * 取消视频推荐
     *
     * @param id
     * @return
     */
    public Object cancelVideoRecommend(Integer id) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_cancelVideoRecommend_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        DtsVideo videoOld = videoMapper.selectByPrimaryKey(id);
        if (null == videoOld || videoOld.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("视频不存在或已删除");
        }

        videoOld.setRecommend(false);
        videoOld.setUpdateId(adminId);
        videoOld.setUpdateTime(LocalDateTime.now());
        videoMapper.updateByPrimaryKeySelective(videoOld);

        lock.unlock();
        return ResponseUtil.ok("取消成功", null);
    }

    /**
     * 删除视频
     *
     * @param id
     * @return
     */
    public Object delVideo(Integer id) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_delVideo_" + id);
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        DtsVideo videoOld = videoMapper.selectByPrimaryKey(id);
        if (null == videoOld || videoOld.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("视频不存在或已删除");
        }

        videoOld.setDeleted(true);
        videoOld.setUpdateId(adminId);
        videoOld.setUpdateTime(LocalDateTime.now());
        videoMapper.updateByPrimaryKeySelective(videoOld);

        lock.unlock();
        return ResponseUtil.ok("删除成功", null);
    }


    /**
     * 修改视频
     *
     * @param video
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object updVideo(DtsVideo video) {
        if (null == video.getId() || video.getId().intValue() < 1) {
            return ResponseUtil.fail("参数【id】为空");
        }
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_updVideo_" + video.getId());
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);

        if (StringUtils.isBlank(video.getVideoUrl())) {
            video.setVideoUrl(null);
        }
        if (StringUtils.isBlank(video.getTitle())) {
            video.setTitle(null);
        }
        if (StringUtils.isBlank(video.getCoverUrl())) {
            video.setCoverUrl(null);
        }

        if (!StringUtils.isBlank(video.getTitle()) && video.getTitle().length() > 250) {
            lock.unlock();
            return ResponseUtil.fail("标题最多250字");
        }
        DtsVideo videoOld = videoMapper.selectByPrimaryKey(video.getId());
        if (null == videoOld || videoOld.getDeleted()) {
            lock.unlock();
            return ResponseUtil.fail("视频不存在或已删除");
        }

        if (null != video.getRecommend() && video.getRecommend()) {//如果设置为推荐，就取消当前所有的推荐视频
            DtsVideo updVideo = new DtsVideo();
            updVideo.setRecommend(false);
            updVideo.setUpdateId(adminId);
            updVideo.setUpdateTime(LocalDateTime.now());
            DtsVideoExample updeEample = new DtsVideoExample();
            updeEample.createCriteria().andRecommendEqualTo(true);
            videoMapper.updateByExampleSelective(updVideo, updeEample);
        }
        if (null == video.getSort() || video.getSort().intValue() <= 0) {
            video.setSort(0);
        }
        video.setUpdateId(adminId);
        video.setUpdateTime(LocalDateTime.now());
        videoMapper.updateByPrimaryKeySelective(video);
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }

    /**
     * 品牌视频列表
     *
     * @param page
     * @param size
     * @param title
     * @param recommend
     * @return
     */
    public TableDataInfo getVideoList(Integer page, Integer size, String title, Boolean recommend) {
        DtsVideoExample query = new DtsVideoExample();
        query.setOrderByClause("sort asc,add_time desc");
        DtsVideoExample.Criteria criteria = query.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!StringUtils.isBlank(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (null != recommend) {
            criteria.andRecommendEqualTo(recommend);
        }
        query.or(criteria);
        Page p = PageHelper.startPage(page, size);
        List<DtsVideo> list = videoMapper.selectByExample(query);
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return TableDataInfo.getDataTable(list, p.getTotal());
    }

    /**
     * 获取推荐视频
     *
     * @return
     */
    public Object getRecommendVideo() {
        DtsVideoExample query = new DtsVideoExample();
        query.setOrderByClause("add_time desc");
        query.createCriteria().andDeletedEqualTo(false).andRecommendEqualTo(true);
        return ResponseUtil.ok("查询成功", videoMapper.selectOneByExample(query));
    }


    /**
     * 获取退货地址详情
     *
     * @return
     */
    public Object getReturnAdress() {
        return ResponseUtil.ok(systemConfigService.getReturnAdress());
    }

    /**
     * 修改退货地址
     *
     * @param vo
     * @return
     */
    public Object updReturnAdress(ReturnAdressVo vo) {
        Integer adminId = getAdminId();
        RLock lock = redisson.getLock("admin_updReturnAdress");
        if (lock.isLocked()) {
            return ResponseUtil.frequent("其他管理人员操作中,请稍后再试");
        }
        lock.lock(30, TimeUnit.SECONDS);
        if (StringUtils.isBlank(vo.getName())) {
            lock.unlock();
            return ResponseUtil.fail("请填写收货人姓名");
        }
        if (vo.getName().length() > 20) {
            lock.unlock();
            return ResponseUtil.fail("收货人姓名最多20字");
        }
        if (StringUtils.isBlank(vo.getPhone())) {
            lock.unlock();
            return ResponseUtil.fail("请填写收货电话");
        }
        if (vo.getPhone().length() > 50) {
            lock.unlock();
            return ResponseUtil.fail("收货电话最多50字");
        }

        if (StringUtils.isBlank(vo.getAddress())) {
            lock.unlock();
            return ResponseUtil.fail("请填写收货地址");
        }
        if (vo.getAddress().length() > 500) {
            lock.unlock();
            return ResponseUtil.fail("收货地址最多500字");
        }
        if (!StringUtils.isBlank(vo.getRemarks()) && vo.getRemarks().length() > 500) {
            lock.unlock();
            return ResponseUtil.fail("备注最多500字");
        }
        DtsSystem system = systemConfigService.selectByKey("dts.return.adress");
        if (null == system) {//不存在就新增
            system = new DtsSystem();
            system.setKeyName("dts.return.adress");
            system.setAddTime(LocalDateTime.now());
            system.setDeleted(false);
            system.setUpdateTime(LocalDateTime.now());
            system.setKeyValue(JSON.toJSONString(vo));
            systemConfigService.insertSelective(system);
        } else {//存在就修改
            system.setUpdateTime(LocalDateTime.now());
            system.setKeyValue(JSON.toJSONString(vo));
            systemConfigService.updateByPrimaryKeySelective(system);
        }
        lock.unlock();
        return ResponseUtil.ok("修改成功", null);
    }


}
